package com.andy.module.progress

import okhttp3.MediaType
import okhttp3.RequestBody
import okio.BufferedSink
import okio.Okio
import okio.buffer

/**
 * @creator:LuoFan
 * @date:2022/6/9
 * @description:
 */
class ProgressRequestBody(var body: RequestBody, var listener: ProgressListener?) : RequestBody() {

    //刷新进度间隔
    var refreshTime = 200

    override fun contentType(): MediaType? {
        return body.contentType()
    }

    override fun contentLength(): Long {
        return body.contentLength()
    }

    override fun writeTo(sink: BufferedSink) {
        if (listener == null) {
            return body.writeTo(sink)
        } else {
            val progressSink = ProgressSink(sink, body.contentLength(), listener)
            progressSink.refreshTime = refreshTime
            val buffer = progressSink.buffer()
            body.writeTo(buffer)
            buffer.flush()
        }
    }
}